<template>
  <view class="chart-container">
    <view class="echart" id="ring-chart"></view>
  </view>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'ChartComponent',
  props: {
    deviceStatus: {
      type: Object,
      required: true,
      default: () => ({
        online: 0,
        offline: 0,
        alarm: 0
      })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      // 初始化图表
      const chartDom = document.getElementById('ring-chart')
      this.chart = echarts.init(chartDom)
      this.updateChart()
    },
    updateChart() {
      // 更新图表配置
      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {
                value: this.deviceStatus.online,
                name: '在线',
                itemStyle: { color: '#07c160' }
              },
              {
                value: this.deviceStatus.offline,
                name: '离线',
                itemStyle: { color: '#ff976a' }
              },
              {
                value: this.deviceStatus.alarm,
                name: '报警',
                itemStyle: { color: '#ee0a24' }
              }
            ]
          }
        ]
      }
      this.chart && this.chart.setOption(option)
    }
  },
  watch: {
    deviceStatus: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.updateChart()
        })
      }
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;

  .echart {
    width: 100%;
    height: 300rpx;
  }
}
</style>
